<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h2>仪表盘</h2>
      <p>欢迎来到商品管理系统后台</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <p class="stat-label">商品总数</p>
            <h3 class="stat-value">{{ productCount }}</h3>
          </div>
          <el-icon class="stat-icon"><ShoppingBag /></el-icon>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <p class="stat-label">订单总数</p>
            <h3 class="stat-value">{{ orderCount }}</h3>
          </div>
          <el-icon class="stat-icon"><Document /></el-icon>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <p class="stat-label">成交总金额</p>
            <h3 class="stat-value">¥{{ totalSales }}</h3>
          </div>
          <el-icon class="stat-icon"><Wallet /></el-icon>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <p class="stat-label">用户总数</p>
            <h3 class="stat-value">{{ userCount }}</h3>
          </div>
          <el-icon class="stat-icon"><User /></el-icon>
        </div>
      </el-card>
    </div>

    <!-- 统计图表 -->
    <div class="charts-container">
      <!-- 柱状图：月度销售数据 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>月度销售数据</span>
          </div>
        </template>
        <div class="chart-content">
          <div class="bar-chart">
            <div v-for="item in monthlySalesData" :key="item.month" class="bar-container">
              <div class="bar" :style="{ height: item.sales * 0.08 + 'px' }"></div>
              <div class="bar-label">{{ item.month }}</div>
              <div class="bar-value">{{ item.sales }}</div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 饼图：本周收入分布 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>本周收入分布</span>
          </div>
        </template>
        <div class="chart-content">
          <div class="pie-chart-container">
            <!-- SVG 饼图实现 -->
            <svg class="native-pie-chart" viewBox="0 0 250 250">
              <g v-for="(item, index) in weeklyIncomeData" :key="item.name">
                <!-- 饼图切片 -->
                <path
                  :d="getPieSlicePath(item.startAngle, item.endAngle)"
                  :fill="getItemColor(item.name)"
                  class="pie-slice"
                  :data-name="item.name"
                />
                <!-- 连接标签的线 -->
                <line
                  :x1="getLabelPosition(item.startAngle, item.endAngle).cx"
                  :y1="getLabelPosition(item.startAngle, item.endAngle).cy"
                  :x2="getLabelPosition(item.startAngle, item.endAngle).lx"
                  :y2="getLabelPosition(item.startAngle, item.endAngle).ly"
                  stroke="#ccc"
                  stroke-width="1"
                />
                <!-- 标签文本 -->
                <text
                  :x="getLabelPosition(item.startAngle, item.endAngle).lx"
                  :y="getLabelPosition(item.startAngle, item.endAngle).ly"
                  :text-anchor="getLabelPosition(item.startAngle, item.endAngle).lx > 125 ? 'end' : 'start'"
                  alignment-baseline="middle"
                  font-size="12"
                  :fill="getItemColor(item.name)"
                  :style="{transform: getLabelPosition(item.startAngle, item.endAngle).lx > 125 ? 'translateX(-5px)' : 'translateX(5px)'}"
                >
                  {{ item.name }}
                </text>
              </g>
            </svg>
            <!-- 图例 -->
            <div class="pie-legend">
              <div v-for="item in weeklyIncomeData" :key="item.name" class="legend-item">
                <span class="legend-color" :style="{ backgroundColor: getItemColor(item.name) }"></span>
                <span class="legend-name">{{ item.name }}</span>
                <span class="legend-value">¥{{ item.value }} ({{ getItemPercentage(item.value) }}%)</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 最近订单 -->
    <div class="recent-orders">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>最近订单</span>
            <el-button type="text" @click="goToOrders">查看全部</el-button>
          </div>
        </template>
        <el-table :data="recentOrders" style="width: 100%">
          <el-table-column prop="id" label="订单ID" width="120" />
          <el-table-column prop="orderNo" label="订单编号" width="180" />
          <el-table-column prop="totalPrice" label="订单金额" />
          <el-table-column prop="state" label="订单状态" />
          <el-table-column prop="createTime" label="创建时间" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  ShoppingBag,
  Document,
  User,
  Message,
  Wallet
} from '@element-plus/icons-vue';

const router = useRouter();

// 统计数据
const productCount = ref(0);
const orderCount = ref(0);
const userCount = ref(0);
const commentCount = ref(0);
const totalSales = ref(0);

// 最近订单数据
const recentOrders = ref<Array<any>>([]);

// 月度销售数据 - 用于柱状图
const monthlySalesData = ref<Array<{
  month: string;
  sales: number;
}>>([]);

// 订单状态分布数据
const orderStatusData = ref<Array<{
  name: string;
  value: number;
}>>([]);

// 本周收入数据 - 用于饼图
const weeklyIncomeData = ref<Array<{
  name: string;
  value: number;
  startAngle: number;
  endAngle: number;
}>>([]);

// 本周总收入
const weeklyTotalIncome = ref(0);

// 获取颜色映射 - 包含星期几的颜色
const getItemColor = (name: string) => {
  const colorMap: Record<string, string> = {
    '周一': '#2196F3', // 蓝色
    '周二': '#4CAF50', // 绿色
    '周三': '#FF9800', // 橙色
    '周四': '#F44336', // 红色
    '周五': '#9E9E9E', // 深灰色
    '周六': '#FFC107', // 黄色
    '周日': '#607D8B', // 蓝灰色
    '已完成': '#409EFF',
    '已发货': '#67C23A',
    '待付款': '#E6A23C',
    '已取消': '#F56C6C'
  };
  return colorMap[name] || '#909399';
};

// 生成饼图切片的SVG路径
const getPieSlicePath = (startAngle: number, endAngle: number) => {
  const centerX = 125;
  const centerY = 125;
  const radius = 80;
  
  // 角度转换为弧度
  const startRad = (startAngle - 90) * Math.PI / 180;
  const endRad = (endAngle - 90) * Math.PI / 180;
  
  // 计算弧的起点和终点坐标
  const startX = centerX + radius * Math.cos(startRad);
  const startY = centerY + radius * Math.sin(startRad);
  const endX = centerX + radius * Math.cos(endRad);
  const endY = centerY + radius * Math.sin(endRad);
  
  // 确定是否使用大弧（大于180度）
  const largeArcFlag = endAngle - startAngle <= 180 ? 0 : 1;
  
  // 创建SVG路径
  return `M ${centerX} ${centerY} L ${startX} ${startY} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${endX} ${endY} Z`;
};

// 计算标签位置
const getLabelPosition = (startAngle: number, endAngle: number) => {
  const centerX = 125;
  const centerY = 125;
  const radius = 80;
  const labelRadius = radius + 30;
  
  // 计算中间角度
  const midAngle = (startAngle + endAngle) / 2;
  const midRad = (midAngle - 90) * Math.PI / 180;
  
  // 计算饼图边缘的中心点
  const cx = centerX + radius * Math.cos(midRad);
  const cy = centerY + radius * Math.sin(midRad);
  
  // 计算标签位置
  const lx = centerX + labelRadius * Math.cos(midRad);
  const ly = centerY + labelRadius * Math.sin(midRad);
  
  return { cx, cy, lx, ly };
};

// 计算百分比
const getItemPercentage = (value: number) => {
  const total = weeklyTotalIncome.value;
  return ((value / total) * 100).toFixed(1);
};

// 不需要额外的角度计算函数，直接使用weeklyIncomeData中的角度信息

// 加载统计数据 - 完全使用本地模拟数据，不依赖外部API
const loadStats = () => {
  try {
    // 直接设置模拟的统计数据
    productCount.value = 50;  // 模拟商品总数
    orderCount.value = 200;   // 模拟订单总数
    userCount.value = 100;    // 模拟用户总数
    commentCount.value = 350; // 模拟评论总数
    totalSales.value = 15860.50; // 模拟成交总金额
  } catch (error) {
    ElMessage.error('加载统计数据失败');
    console.error('加载统计数据失败:', error);
  }
};

// 加载图表数据
const loadChartData = () => {
  try {
    // 模拟月度销售数据 - 柱状图
    monthlySalesData.value = [
      { month: '1月', sales: 1200 },
      { month: '2月', sales: 1900 },
      { month: '3月', sales: 1500 },
      { month: '4月', sales: 2300 },
      { month: '5月', sales: 2900 },
      { month: '6月', sales: 2800 }
    ];

    // 模拟订单状态分布数据
    orderStatusData.value = [
      { name: '已完成', value: 120 },
      { name: '已发货', value: 40 },
      { name: '待付款', value: 25 },
      { name: '已取消', value: 15 }
    ];

    // 模拟本周收入分布数据 - 用于饼图
    const incomeData = [
      { name: '周一', value: 1850 },
      { name: '周二', value: 2100 },
      { name: '周三', value: 1650 },
      { name: '周四', value: 2400 },
      { name: '周五', value: 2900 },
      { name: '周六', value: 3200 },
      { name: '周日', value: 2800 }
    ];
    
    // 计算总收入
    weeklyTotalIncome.value = incomeData.reduce((sum, item) => sum + item.value, 0);
    
    // 计算每个部分的角度
    let currentAngle = 0; // 从右侧开始
  weeklyIncomeData.value = incomeData.map(item => {
    const percentage = item.value / weeklyTotalIncome.value;
    const angle = percentage * 360;
    const startAngle = currentAngle;
    const endAngle = currentAngle + angle;
    currentAngle = endAngle;
    return {
      ...item,
      startAngle,
      endAngle,
      percentage: percentage * 100
    };
  });
  } catch (error) {
    ElMessage.error('加载图表数据失败');
    console.error('加载图表数据失败:', error);
  }
};

// 加载最近订单 - 完全使用本地模拟数据，不依赖外部API
const loadRecentOrders = () => {
  try {
    // 直接设置模拟的订单数据
    recentOrders.value = [
      { 
        id: 1, 
        orderNo: 'ORD202306010001', 
        totalPrice: 299.00, 
        state: '已完成', 
        createTime: '2023-06-01 10:30:00'
      },
      { 
        id: 2, 
        orderNo: 'ORD202305310002', 
        totalPrice: 199.50, 
        state: '已完成', 
        createTime: '2023-05-31 15:45:00'
      },
      { 
        id: 3, 
        orderNo: 'ORD202305300003', 
        totalPrice: 599.00, 
        state: '已发货', 
        createTime: '2023-05-30 09:15:00'
      },
      { 
        id: 4, 
        orderNo: 'ORD202305290004', 
        totalPrice: 89.90, 
        state: '待付款', 
        createTime: '2023-05-29 14:20:00'
      },
      { 
        id: 5, 
        orderNo: 'ORD202305280005', 
        totalPrice: 1299.00, 
        state: '已完成', 
        createTime: '2023-05-28 11:30:00'
      }
    ];
  } catch (error) {
    ElMessage.error('加载最近订单失败');
    console.error('加载最近订单失败:', error);
  }
};

// 跳转到订单列表
const goToOrders = () => {
  router.push('/admin/orders/list');
};

// 组件挂载时加载数据
onMounted(() => {
  loadStats();
  loadRecentOrders();
  loadChartData();
});
</script>

<style scoped>
.dashboard-container {
  width: 100%;
}

.dashboard-header {
  margin-bottom: 20px;
}

.dashboard-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.dashboard-header p {
  margin: 5px 0 0;
  color: #666;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.stat-info {
  flex: 1;
}

.stat-label {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stat-value {
  margin: 5px 0 0;
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.stat-icon {
  font-size: 36px;
  color: #409eff;
}

/* 图表样式 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
  display: flex;
  flex-direction: column;
}

.chart-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

/* 柱状图样式 */
.bar-chart {
  width: 100%;
  height: 250px;
  display: flex;
  align-items: flex-end;
  justify-content: space-around;
  padding-bottom: 20px;
}

.bar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 60px;
}

.bar {
  width: 40px;
  background: linear-gradient(to top, #409eff, #69b1ff);
  border-radius: 4px 4px 0 0;
  transition: height 0.5s ease;
}

.bar-label {
  margin-top: 10px;
  font-size: 12px;
  color: #666;
}

.bar-value {
  margin-top: 5px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

/* 饼图容器样式 */
.pie-chart-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 20px;
}

/* 原生饼图样式 */
.native-pie-chart {
  width: 250px;
  height: 250px;
}

.pie-slice {
  transition: opacity 0.3s, transform 0.3s;
  cursor: pointer;
}

.pie-slice:hover {
  opacity: 0.8;
  transform: scale(1.02);
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.total-label {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

/* 图例样式 */
.pie-legend {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-width: 200px;
  flex: 1;
  min-width: 180px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.legend-item:hover {
  background-color: #f5f7fa;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 10px;
}

.legend-name {
  flex: 1;
  font-size: 14px;
}

.legend-value {
  font-size: 14px;
  color: #666;
}

.recent-orders {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-weight: bold;
}
</style>